package com.tanhua.dubbo.api;

import com.tanhua.model.db.Question;
import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendsApiImpl implements FriendsApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void save(Long userId, Long nowId) {
        //添加当前用户的好友记录
        Criteria criteria1 = Criteria.where("userId").is(nowId).and("friendId").is(userId);
        Query query1 = Query.query(criteria1);
        if(!mongoTemplate.exists(query1,Friend.class)){
            Friend friend = new Friend();
            friend.setCreated(System.currentTimeMillis());
            friend.setFriendId(userId);
            friend.setUserId(nowId);
            mongoTemplate.save(friend);
        }

        //为添加好友的用户添加好友记录,判断数据库中是否存在对应的好友记录，
        // 不存在在添加，有可能点击多次添加好友
        Criteria criteria = Criteria.where("userId").is(userId).and("friendId").is(nowId);
        Query query = new Query(criteria);
        boolean exists = mongoTemplate.exists(query, Friend.class);
        if(!exists){
            Friend friend2 = new Friend();
            friend2.setCreated(System.currentTimeMillis());
            friend2.setUserId(userId);
            friend2.setFriendId(nowId);
            mongoTemplate.save(friend2);
        }

    }

    @Override
    public List<Friend> friendPage(Long userId, Integer page, Integer pageSize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .limit(pageSize)
                .skip((page-1)*pageSize);
        //，skip代表从多少条开始，limit每页放多少条
        List<Friend> list = mongoTemplate.find(query, Friend.class);
        return list;
    }
}
